import pandas as pd
import matplotlib.pyplot as plt

# 读取数据
def load_data(file_path):
    try:
        # 使用 pandas 读取 CSV 文件
        data = pd.read_csv(file_path)
        print(f"成功读取文件: {file_path}")
        return data
    except Exception as e:
        print(f"读取文件时出错: {file_path}, 错误信息: {e}")
        return None

# 主程序
if __name__ == "__main__":
    # 读取数据
    data_france = load_data("./sensitivity_analysis/data/predictions_France.csv")
    data_usa = load_data("./sensitivity_analysis/data/predictions_United States.csv")
    data_china = load_data("./sensitivity_analysis/data/predictions_China.csv")

    # 检查数据是否成功读取
    if data_france is not None and data_usa is not None and data_china is not None:
        # 合并数据
        data_france['Host'] = 'France'
        data_usa['Host'] = 'United States'
        data_china['Host'] = 'China'
        combined_data = pd.concat([data_france, data_usa, data_china], ignore_index=True)

        # 计算影响因子
        combined_data['Medal_Influence'] = combined_data['Total_Medals'] / combined_data.groupby('Host')['Total_Medals'].transform('mean')

        # 灵敏度检验
        sensitivity_analysis = combined_data.groupby(['Host', 'Country'])['Medal_Influence'].mean().unstack()

        # 可视化结果
        ax = sensitivity_analysis.plot(kind='bar', figsize=(12, 8))
        plt.title('Sensitivity Analysis of Medal Influence by Host Country')
        plt.xlabel('Host Country')
        plt.ylabel('Average Medal Influence')

        # 调整图例位置
        plt.legend(title='Country', bbox_to_anchor=(1.05, 1), loc='upper left')

        # 显示图表
        plt.tight_layout()
        plt.show()

        # 打印影响因子
        print("影响因子分析结果：")
        print(sensitivity_analysis)
    else:
        print("部分数据读取失败，请检查文件路径和文件格式。")